<template>
    <view class="container">
      <app-header title="考试管理" />
      
      <view class="action-container">
        <button class="btn-add" @click="openAddExamModal">添加考试</button>
      </view>
      
      <view class="filter-container">
        <view class="search-box">
          <input 
            class="search-input" 
            type="text" 
            v-model="searchKeyword" 
            placeholder="搜索考试名称" 
            @input="handleSearch"
          />
          <text class="search-icon">🔍</text>
        </view>
        
        <view class="filter-options">
          <picker 
            mode="selector" 
            :range="statusOptions" 
            range-key="label" 
            :value="statusIndex" 
            @change="handleStatusChange"
          >
            <view class="filter-item">
              <text>状态：</text>
              <text>{{ statusOptions[statusIndex].label }}</text>
            </view>
          </picker>
          
          <picker 
            mode="selector" 
            :range="examTypeOptions" 
            range-key="label" 
            :value="examTypeIndex" 
            @change="handleExamTypeChange"
          >
            <view class="filter-item">
              <text>科目：</text>
              <text>{{ examTypeOptions[examTypeIndex].label }}</text>
            </view>
          </picker>
        </view>
      </view>
      
      <view v-if="loading" class="loading-container">
        <loading-state />
      </view>
      
      <view v-else-if="exams.length === 0" class="empty-container">
        <empty-state text="暂无考试数据" buttonText="添加考试" @buttonClick="openAddExamModal" />
      </view>
      
      <view v-else class="exam-list">
        <view 
          class="exam-item card" 
          v-for="(item, index) in exams" 
          :key="index"
          @click="viewExamDetail(item)"
        >
          <view class="exam-header">
            <view class="exam-name">{{ item.name }}</view>
            <status-badge :status="item.status" type="exam" />
          </view>
          
          <view class="exam-info">
            <view class="info-item">
              <text class="info-label">考试科目：</text>
              <text class="info-value">{{ getExamTypeText(item.exam_type) }}</text>
            </view>
            <view class="info-item">
              <text class="info-label">考试时间：</text>
              <text class="info-value">{{ formatDate(item.exam_date) }}</text>
            </view>
            <view class="info-item">
              <text class="info-label">报名截止：</text>
              <text class="info-value">{{ formatDate(item.registration_deadline) }}</text>
            </view>
            <view class="info-item">
              <text class="info-label">报名人数：</text>
              <text class="info-value">{{ item.current_applicants }}/{{ item.max_applicants }}</text>
            </view>
          </view>
          
          <view class="exam-actions">
            <button 
              class="btn-action btn-view" 
              @click.stop="viewExamDetail(item)"
            >
              查看
            </button>
            <button 
              class="btn-action btn-edit" 
              v-if="item.status === 'upcoming'"
              @click.stop="editExam(item)"
            >
              编辑
            </button>
            <button 
              class="btn-action btn-cancel" 
              v-if="item.status === 'upcoming'"
              @click.stop="cancelExam(item)"
            >
              取消
            </button>
          </view>
        </view>
      </view>
      
      <!-- 分页 -->
      <view class="pagination" v-if="exams.length > 0">
        <button 
          class="btn-page" 
          :disabled="page <= 1"
          @click="prevPage"
        >
          上一页
        </button>
        <text class="page-info">{{ page }}/{{ totalPages }}</text>
        <button 
          class="btn-page" 
          :disabled="page >= totalPages"
          @click="nextPage"
        >
          下一页
        </button>
      </view>
      
      <!-- 添加考试弹窗 -->
      <uni-popup ref="addExamPopup" type="bottom">
        <view class="add-exam-container">
          <view class="add-exam-title">添加考试</view>
          
          <view class="form-item">
            <view class="form-label">考试名称</view>
            <input 
              class="input" 
              type="text" 
              v-model="examForm.name" 
              placeholder="请输入考试名称" 
            />
          </view>
          
          <view class="form-item">
            <view class="form-label">考试科目</view>
            <picker 
              mode="selector" 
              :range="examTypeOptions.slice(1)" 
              range-key="label" 
              :value="examTypeFormIndex" 
              @change="handleExamTypeFormChange"
            >
              <view class="picker-value">
                {{ examTypeFormIndex >= 0 ? examTypeOptions[examTypeFormIndex + 1].label : '请选择考试科目' }}
              </view>
            </picker>
          </view>
          
          <view class="form-item">
            <view class="form-label">考试时间</view>
            <picker 
              mode="datetime" 
              :value="examForm.exam_date" 
              @change="handleExamDateChange"
            >
              <view class="picker-value">
                {{ examForm.exam_date || '请选择考试时间' }}
              </view>
            </picker>
          </view>
          
          <view class="form-item">
            <view class="form-label">报名截止时间</view>
            <picker 
              mode="datetime" 
              :value="examForm.registration_deadline" 
              @change="handleDeadlineChange"
            >
              <view class="picker-value">
                {{ examForm.registration_deadline || '请选择报名截止时间' }}
              </view>
            </picker>
          </view>
          
          <view class="form-item">
            <view class="form-label">考试地点</view>
            <input 
              class="input" 
              type="text" 
              v-model="examForm.location" 
              placeholder="请输入考试地点" 
            />
          </view>
          
          <view class="form-item">
            <view class="form-label">最大报名人数</view>
            <input 
              class="input" 
              type="number" 
              v-model="examForm.max_applicants" 
              placeholder="请输入最大报名人数" 
            />
          </view>
          
          <view class="form-item">
            <view class="form-label">考试说明</view>
            <textarea 
              class="textarea" 
              v-model="examForm.description" 
              placeholder="请输入考试说明" 
            />
          </view>
          
          <view class="add-exam-actions">
            <button class="btn-cancel" @click="closeAddExamModal">取消</button>
            <button 
              class="btn-submit" 
              :loading="submitting" 
              :disabled="submitting" 
              @click="submitExam"
            >
              提交
            </button>
          </view>
        </view>
      </uni-popup>
    </view>
  </template>
  
  <script>
  import { mapGetters } from 'vuex';
  import { formatDate } from '@/utils/date';
  import config from '@/config/index';
  import AppHeader from '@/components/common/AppHeader';
  import LoadingState from '@/components/common/LoadingState';
  import EmptyState from '@/components/common/EmptyState';
  import StatusBadge from '@/components/business/StatusBadge';
  
  export default {
    components: {
      AppHeader,
      LoadingState,
      EmptyState,
      StatusBadge
    },
    data() {
      return {
        exams: [],
        total: 0,
        page: 1,
        pageSize: 10,
        loading: true,
        searchKeyword: '',
        statusOptions: [
          { value: '', label: '全部状态' },
          { value: 'upcoming', label: '即将开始' },
          { value: 'ongoing', label: '进行中' },
          { value: 'completed', label: '已结束' },
          { value: 'cancelled', label: '已取消' }
        ],
        statusIndex: 0,
        examTypeOptions: [
          { value: '', label: '全部科目' },
          ...config.examSubjects
        ],
        examTypeIndex: 0,
        examForm: {
          name: '',
          exam_type: '',
          exam_date: '',
          registration_deadline: '',
          location: '',
          max_applicants: '',
          description: ''
        },
        examTypeFormIndex: -1,
        submitting: false
      };
    },
    computed: {
      ...mapGetters('user', [
        'isAdmin'
      ]),
      totalPages() {
        return Math.ceil(this.total / this.pageSize);
      }
    },
    onLoad() {
      if (this.isAdmin) {
        this.loadExams();
      } else {
        this.showToast('您没有管理员权限');
        setTimeout(() => {
          uni.navigateBack();
        }, 1500);
      }
    },
    methods: {
      formatDate,
      getExamTypeText(type) {
        const examType = config.examSubjects.find(item => item.value === type);
        return examType ? examType.label : type;
      },
      loadExams() {
        this.loading = true;
        
        // 准备查询参数
        const params = {
          page: this.page,
          pageSize: this.pageSize
        };
        
        // 添加筛选条件
        if (this.searchKeyword) {
          params.search = this.searchKeyword;
        }
        
        if (this.statusOptions[this.statusIndex].value) {
          params.status = this.statusOptions[this.statusIndex].value;
        }
        
        if (this.examTypeOptions[this.examTypeIndex].value) {
          params.exam_type = this.examTypeOptions[this.examTypeIndex].value;
        }
        
        // 这里简化处理，实际项目中应该从API获取数据
        setTimeout(() => {
          // 模拟数据
          const mockData = {
            list: [
              {
                id: 1,
                name: '2025年5月科目一考试',
                exam_type: 'subject1',
                description: '2025年5月科目一考试，请携带身份证准时参加',
                exam_date: '2025-05-15 09:00:00',
                registration_deadline: '2025-05-10 18:00:00',
                max_applicants: 100,
                current_applicants: 50,
                location: '北京市海淀区驾考中心',
                status: 'upcoming'
              },
              {
                id: 2,
                name: '2025年5月科目二考试',
                exam_type: 'subject2',
                description: '2025年5月科目二考试，请携带身份证准时参加',
                exam_date: '2025-05-20 09:00:00',
                registration_deadline: '2025-05-15 18:00:00',
                max_applicants: 50,
                current_applicants: 30,
                location: '北京市海淀区驾考中心',
                status: 'upcoming'
              },
              {
                id: 3,
                name: '2025年4月科目一考试',
                exam_type: 'subject1',
                description: '2025年4月科目一考试，请携带身份证准时参加',
                exam_date: '2025-04-15 09:00:00',
                registration_deadline: '2025-04-10 18:00:00',
                max_applicants: 100,
                current_applicants: 100,
                location: '北京市海淀区驾考中心',
                status: 'completed'
              }
            ],
            total: 3,
            page: 1,
            pageSize: 10
          };
          
          this.exams = mockData.list;
          this.total = mockData.total;
          this.loading = false;
        }, 1000);
      },
      handleSearch() {
        this.page = 1;
        this.loadExams();
      },
      handleStatusChange(e) {
        this.statusIndex = e.detail.value;
        this.page = 1;
        this.loadExams();
      },
      handleExamTypeChange(e) {
        this.examTypeIndex = e.detail.value;
        this.page = 1;
        this.loadExams();
      },
      prevPage() {
        if (this.page > 1) {
          this.page--;
          this.loadExams();
        }
      },
      nextPage() {
        if (this.page < this.totalPages) {
          this.page++;
          this.loadExams();
        }
      },
      viewExamDetail(exam) {
        uni.navigateTo({
          url: `/pages/admin/exam-detail?id=${exam.id}`
        });
      },
      editExam(exam) {
        // 填充表单
        this.examForm = {
          name: exam.name,
          exam_type: exam.exam_type,
          exam_date: exam.exam_date,
          registration_deadline: exam.registration_deadline,
          location: exam.location,
          max_applicants: exam.max_applicants,
          description: exam.description
        };
        
        // 设置科目索引
        const typeIndex = this.examTypeOptions.findIndex(item => item.value === exam.exam_type);
        this.examTypeFormIndex = typeIndex > 0 ? typeIndex - 1 : 0;
        
        // 打开弹窗
        this.$refs.addExamPopup.open();
      },
      cancelExam(exam) {
        this.showModal(`确认取消 "${exam.name}" 考试吗？取消后不可恢复！`)
          .then(confirm => {
            if (confirm) {
              uni.showLoading({
                title: '处理中...'
              });
              
              // 这里简化处理，实际项目中应该调用API
              setTimeout(() => {
                uni.hideLoading();
                this.showToast('考试已取消', 'success');
                // 重新加载数据
                this.loadExams();
              }, 1000);
            }
          });
      },
      openAddExamModal() {
        // 重置表单
        this.examForm = {
          name: '',
          exam_type: '',
          exam_date: '',
          registration_deadline: '',
          location: '',
          max_applicants: '',
          description: ''
        };
        this.examTypeFormIndex = -1;
        
        // 打开弹窗
        this.$refs.addExamPopup.open();
      },
      closeAddExamModal() {
        this.$refs.addExamPopup.close();
      },
      handleExamTypeFormChange(e) {
        this.examTypeFormIndex = e.detail.value;
        this.examForm.exam_type = this.examTypeOptions[this.examTypeFormIndex + 1].value;
      },
      handleExamDateChange(e) {
        this.examForm.exam_date = e.detail.value;
      },
      handleDeadlineChange(e) {
        this.examForm.registration_deadline = e.detail.value;
      },
      submitExam() {
        // 表单验证
        if (!this.examForm.name) {
          this.showToast('请输入考试名称');
          return;
        }
        
        if (!this.examForm.exam_type) {
          this.showToast('请选择考试科目');
          return;
        }
        
        if (!this.examForm.exam_date) {
          this.showToast('请选择考试时间');
          return;
        }
        
        if (!this.examForm.registration_deadline) {
          this.showToast('请选择报名截止时间');
          return;
        }
        
        if (!this.examForm.location) {
          this.showToast('请输入考试地点');
          return;
        }
        
        if (!this.examForm.max_applicants) {
          this.showToast('请输入最大报名人数');
          return;
        }
        
        // 比较时间
        const examDate = new Date(this.examForm.exam_date);
        const deadline = new Date(this.examForm.registration_deadline);
        
        if (deadline >= examDate) {
          this.showToast('报名截止时间必须早于考试时间');
          return;
        }
        
        this.submitting = true;
        
        // 这里简化处理，实际项目中应该调用API
        setTimeout(() => {
          this.submitting = false;
          this.closeAddExamModal();
          this.showToast('考试添加成功', 'success');
          // 重新加载数据
          this.loadExams();
        }, 1000);
      }
    }
  };
</script>

<style lang="scss">
.container {
  padding: 30rpx;
}

.action-container {
  margin-bottom: 30rpx;
}

.btn-add {
  width: 100%;
  height: 80rpx;
  line-height: 80rpx;
  font-size: 28rpx;
  color: #fff;
  background-color: #3c8dbc;
  border-radius: 8rpx;
}

.filter-container {
  margin-bottom: 30rpx;
}

.search-box {
  position: relative;
  margin-bottom: 20rpx;
}

.search-input {
  width: 100%;
  height: 80rpx;
  line-height: 80rpx;
  padding: 0 80rpx 0 20rpx;
  font-size: 28rpx;
  color: #333;
  border: 1px solid #ddd;
  border-radius: 8rpx;
  box-sizing: border-box;
}

.search-icon {
  position: absolute;
  right: 20rpx;
  top: 20rpx;
  font-size: 40rpx;
  color: #999;
}

.filter-options {
  display: flex;
  justify-content: space-between;
}

.filter-item {
  display: flex;
  align-items: center;
  font-size: 28rpx;
  padding: 20rpx 0;
}

.loading-container, .empty-container {
  padding: 60rpx 0;
}

.exam-list {
  margin-bottom: 40rpx;
}

.exam-item {
  padding: 30rpx;
  margin-bottom: 20rpx;
}

.exam-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.exam-name {
  font-size: 32rpx;
  font-weight: bold;
}

.exam-info {
  margin-bottom: 20rpx;
}

.info-item {
  display: flex;
  margin-bottom: 10rpx;
}

.info-label {
  width: 160rpx;
  font-size: 28rpx;
  color: #666;
}

.info-value {
  flex: 1;
  font-size: 28rpx;
  color: #333;
}

.exam-actions {
  display: flex;
  justify-content: flex-end;
}

.btn-action {
  margin-left: 20rpx;
  font-size: 26rpx;
  padding: 10rpx 30rpx;
  border-radius: 6rpx;
}

.btn-view {
  color: #666;
  background-color: #f8f8f8;
  border: 1px solid #ddd;
}

.btn-edit {
  color: #fff;
  background-color: #3c8dbc;
}

.btn-cancel {
  color: #fff;
  background-color: #f56c6c;
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 30rpx;
  margin-bottom: 30rpx;
}

.btn-page {
  font-size: 28rpx;
  color: #666;
  background-color: #f8f8f8;
  border: 1px solid #ddd;
  border-radius: 6rpx;
  padding: 10rpx 30rpx;
}

.page-info {
  margin: 0 30rpx;
  font-size: 28rpx;
  color: #666;
}

.add-exam-container {
  background-color: #fff;
  border-radius: 10rpx 10rpx 0 0;
  padding: 30rpx;
}

.add-exam-title {
  font-size: 32rpx;
  font-weight: bold;
  text-align: center;
  margin-bottom: 30rpx;
}

.form-item {
  margin-bottom: 30rpx;
}

.form-label {
  font-size: 28rpx;
  color: #666;
  margin-bottom: 10rpx;
}

.input {
  width: 100%;
  height: 90rpx;
  line-height: 90rpx;
  padding: 0 20rpx;
  font-size: 28rpx;
  color: #333;
  border: 1px solid #ddd;
  border-radius: 8rpx;
  box-sizing: border-box;
}

.picker-value {
  width: 100%;
  height: 90rpx;
  line-height: 90rpx;
  padding: 0 20rpx;
  font-size: 28rpx;
  color: #333;
  border: 1px solid #ddd;
  border-radius: 8rpx;
  box-sizing: border-box;
}

.textarea {
  width: 100%;
  height: 180rpx;
  padding: 20rpx;
  font-size: 28rpx;
  color: #333;
  border: 1px solid #ddd;
  border-radius: 8rpx;
  box-sizing: border-box;
}

.add-exam-actions {
  display: flex;
  justify-content: space-between;
  margin-top: 40rpx;
}

.btn-cancel, .btn-submit {
  width: 48%;
  height: 90rpx;
  line-height: 90rpx;
  font-size: 32rpx;
  border-radius: 8rpx;
}

.btn-cancel {
  color: #666;
  background-color: #f8f8f8;
  border: 1px solid #ddd;
}

.btn-submit {
  color: #fff;
  background-color: #3c8dbc;
}
</style>